<script setup lang="ts">
import { handleApiError, sysApi } from '@/api'
import { message } from '@/utils/message'
import { redirectTo } from '@/utils/navigation'
import { storage } from '@/utils/storage'
import { md5 } from 'js-md5'
import { computed, ref } from 'vue'

const form = ref()

// 表单数据
const formData = ref({
  account: 'JL77607613',
  password: 'xmzhao@2025',
})

const rules = {
  account: {
    rules: [
      {
        required: true,
        errorMessage: '请填写姓名',
      },
    ],
  },
  password: {
    required: true,
    message: '请输入密码',
  },
}

// 按钮是否禁用
const isDisabled = computed(() => {
  return !formData.value.account || !formData.value.password
})

// 处理登录
async function handleLogin() {
  const formData = await form.value?.validate()

  const [error, result] = await sysApi.login({
    account: formData.account,
    password: md5(formData.password),
  })

  if (error) {
    return handleApiError(error)
  }

  storage.set('token', result.data.token)

  message.success('登录成功')

  redirectTo({
    url: '/pages/tabBar/courseSchedule/index',
  })
}
</script>

<template>
  <view class="login-container">
    <view class="logo">
      <image src="@/static/images/logo.png" mode="widthFix" />
    </view>
    <view class="title">
      欢迎来到智牛英语！
    </view>

    <uni-forms ref="form" :model-value="formData" :rules="rules" class="form-card">
      <uni-forms-item name="account">
        <uni-easyinput v-model="formData.account" type="text" placeholder="请输入用户账号/手机号" maxlength="12" />
      </uni-forms-item>
      <uni-forms-item name="password">
        <uni-easyinput v-model="formData.password" type="password" placeholder="请输入密码" maxlength="20" />
      </uni-forms-item>
    </uni-forms>
    <button
      class="login-btn"
      :class="{ disabled: isDisabled }"
      :disabled="isDisabled"
      @click="handleLogin"
    >
      登录
    </button>

    <!-- <view v-if="false" class="actions">
      <text class="forget-pwd" @click="handleForgetPwd">
        忘记密码？
      </text>
      <text class="register" @click="handleRegister">
        立即注册
      </text>
    </view> -->
  </view>
</template>

<style lang="scss">
.login-container {
  min-height: 100vh;
  background-color: $uni-color-primary;
  box-sizing: border-box;
  padding: 40rpx;
}

.title{
  color: #fff;
  text-align: center;
  line-height: 100rpx;
  margin-bottom: 30rpx;
  font-size: 34rpx;
}

.logo{
  width: 220rpx;
  height: 220rpx;
  margin: 60rpx auto 30rpx;
  image{
    width: 100%;
    height: 100%;
  }
}

.form-card{
    background-color: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    padding: 60rpx 40rpx 20rpx;
    margin-bottom: 40rpx;
}

.actions {
  display: flex;
  justify-content: space-between;
  margin-top: 40rpx;
  font-size: 28rpx;

  .forget-pwd, .register {
    color: #fff;
  }
}
</style>
